package org.skydiveapplibrary.util;

import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CsvSerializer
{
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	
	private Writer _writer;
	
	public CsvSerializer(Writer writer)
	{
		_writer = writer;
	}
	
	public void addRow(String[] data)
		throws IOException
	{
		_writer.write(commaSeparated(data));
		_writer.write("\n");
	}
	
	public static String formatString(String str)
	{
		return escapeString(str);
	}

	public static String formatInteger(Integer i)
	{
		return i.toString();
	}

	public static String formatBoolean(boolean bool, String yesString, String noString)
	{
		if (bool)
			return yesString; 
		else
			return noString;
	}

	public static String formatDate(Date date)
	{
		return dateFormat.format(date);
	}

	private String commaSeparated(String[] data)
	{
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < data.length; i++)
		{
			builder.append(data[i]);
			if (i < data.length - 1)
			{
				builder.append(",");
			}
		}
		return builder.toString();
	}

	private static String escapeString(String str)
	{
		// if null, return empty string
		if (str == null)
			return "";
		
		// replace " with ""
		str = str.replaceAll("\"", "\"\"");
		// if , or newline, surround with ""
		if (str.contains(",") || str.contains("\n"))
			str = "\"" + str + "\"";
		return str;
	}
}
